const express = require('express');
const bodyParser = require('body-parser');
const app = express();

// 模板引擎配置
app.set('view engine', 'ejs');
app.set('views', './templates');
// 请求体解析中间件配置
app.use(bodyParser());

// 留言内容
const message = [];

// 首页路由
app.get('/', (req, resp) => {
    resp.render('index', {message});
});

// 留言页路由
app.route('/publish').get((req, resp) => {
    resp.render('publish');
})
    .post((req, resp) => {
        if (!req.body.name || !req.body.content) {
            throw new Error('请将所有选项填写完整');
        }
        const now = (new Date()).toLocaleString();
        message.push({
            name: req.body.name,
            content: req.body.content,
            time: now
        });
        resp.redirect('/');
    });

// 开启监听
app.listen(8080, () => {
    console.log('listen on 8080')
});
